package com.bckj.fastboot.core.extra.txasync.service;

import com.bckj.fastboot.core.extra.txasync.TxAsyncRunner;
import com.bckj.fastboot.core.extra.txasync.entity.AsyncInvocation;
import com.bckj.fastboot.core.extra.txasync.repo.AsyncInvocationRepository;
import com.bckj.fastboot.core.util.TransactionUtils;
import lombok.RequiredArgsConstructor;

@RequiredArgsConstructor
public class AsyncInvocationService {

    private final AsyncInvocationRepository asyncInvocationRepository;
    private final TxAsyncRunner txAsyncRunner;

    /**
     * 执行异步任务
     */
    public void execute(AsyncInvocation asyncInvocation, Runnable runnable) {
        boolean r = asyncInvocationRepository.save(asyncInvocation);
        if (!r) {
            throw new RuntimeException("任务执行失败，插入数据库失败");
        }
        TransactionUtils.afterCommit(() -> txAsyncRunner.execute(asyncInvocation, runnable));
    }

    /**
     * 手动重试
     */
    public void retry(String taskId) {
        txAsyncRunner.retry(taskId);
    }

}
